package com.itheima.dao;

import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface IRoleDao {

    /**
     * 查询所有角色信息
     *
     * @return
     */
    @Select("select * from role")
    List<Role> findAllRole();

    /**
     * 添加新角色信息
     *
     * @param role
     */
    @Insert("insert into role(ID, ROLENAME, ROLEDESC) values(SYS_GUID(),#{roleName},#{roleDesc})")
    void insertRole(Role role);

    /**
     * 根据角色id查询角色详情
     *
     * @param roleId 角色id
     * @return
     */
    @Select("select * from role where id = #{roleId}")
    @ResultMap("role_permission")
    Role findByRoleId(String roleId);


    /**
     * 根据用户id查询对应的角色信息
     *
     * @return
     */
    @Select("select * from role where id in(select ROLEID from USERINFO_ROLE where USERID=#{userId})")
    //根据角色查询角色对应的权限
    @Results(id = "role_permission", value = {
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            //根据角色查询权限：多对多
            @Result(property = "permissions", column = "id", javaType = List.class,
                    many = @Many(select = "com.itheima.dao.IPermissionDao.findPermissionByRole", fetchType = FetchType.LAZY))

    })
    List<Role> findRoleByUserInfo();


    /**
     * 根据角色id查询此角色未拥有的权限
     *
     * @param roleId 角色ID
     * @return
     */
    @Select("select * from permission where id not in(select PERMISSIONID from  ROLE_PERMISSION where roleId=#{roleId})")
    List<Permission> findRolePermission(String roleId);


    /**
     * 据角色ID和权限ID，添加此用户未拥有的权限
     *
     * @param roleId     角色ID
     * @param permission 权限ID
     */
    @Insert("insert into ROLE_PERMISSION(PERMISSIONID,ROLEID) values(#{permission},#{roleId})")
    void insertByRoleIdAndPermissionId(@Param("roleId") String roleId, @Param("permission") String permission);
}
